﻿using GoPlay.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace GoPlay.Models
{
    public class InMemoryRepository<T> : IRepository<T> where T : class, IEntity
    {
        private List<T> _db = new List<T>();

        public Exception ExceptionToThrow { get; set; }

        public T GetByID(int id, string[] childCollectionNames)
        {
            return _db.Find(x => x.Id == id);
        }

        public T GetByID(int id)
        {
            if (ExceptionToThrow != null)
                throw ExceptionToThrow;

            return _db.Where(x => x.Id == id).FirstOrDefault(); //_db.Find(x => x.Id == id);

            // http://goneale.com/2009/07/27/linq-to-sql-generic-repository//
            // http://stackoverflow.com/questions/5166297/generic-repository-ef4-ctp5-getbyid
        }

        public List<T> GetAllByUserId(int userId)
        {
            if (ExceptionToThrow != null)
                throw ExceptionToThrow;

            List<T> list = _db.Where(x => x.UserId == userId).ToList();
            return list;
        }

        public void Insert(T entity)
        {
            if (ExceptionToThrow != null)
                throw ExceptionToThrow;

            _db.Add(entity);
        }

        public void SaveChanges()
        {
            if (ExceptionToThrow != null)
                throw ExceptionToThrow;
        }

        public void Delete(T entity)
        {
            if (ExceptionToThrow != null)
                throw ExceptionToThrow;

            _db.Remove(entity);
        }

        public void Update(T entity)
        {
            if (ExceptionToThrow != null)
                throw ExceptionToThrow;

            int pk = entity.Id;
            T o = this.GetByID(entity.Id);
            o = entity;
        }
    }
}